<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">


      <Row  class="query-form">
        <Col span="8">
          <FormItem label="姓名：">
            <Input type="text" v-model="form1.userName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="所在单位：">
            <cascaderDom ref="childOrg" @setOrgInfo="setOrgId" @setOrgname="setOrgName"
                         :orgTree="true"></cascaderDom>
          </FormItem>
        </Col>
        <Col span="8" v-if="switchFlag">
          <FormItem label="专业特长：">
            <Input type="text" v-model="form1.professionDesc"></Input>
          </FormItem>
        </Col>
        <Col span="8" v-else>
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="8" :offset="16" v-show="switchFlag">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>

      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" :loading="buttonLoading" no-data-text="没有查询到相关数据！"
           @on-selection-change='getSelectRows'
           border :columns="columns1" :data="dataTable" size="small">
    </Table>


    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>

    <Modal title="专家信息新增" :transfer=false v-model="model1" :width=600>
      <Form ref="formnew" :model="formnew" :rules="ruleCustom" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="专家姓名：" prop="userId">
              <Input type="text" readonly @on-focus="model4=true" v-model="formnew.userName"/>
              <Input type="text" v-show="false" v-model="formnew.userId"/>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="专业积分：" prop="credits">
              <InputNumber style="width:100%" v-model="formnew.credits"></InputNumber>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around">
          <Col span="23">
            <FormItem label="专业特长：" prop="professionDesc">
              <Input v-model="formnew.professionDesc" type="textarea" :rows="4"/>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="submit('formnew')" :loading="submitButton">确定</Button>
        <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
    <Modal title="专家信息" v-model="model2" :width=800 class="modal-view-detail">
      <Form :model="showdata" :label-width="160">
        <Row type="flex" justify="space-around">
          <Col span="11">
            <FormItem label="专家姓名：">
              {{ showdata.userName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="专业积分：">
              {{ showdata.credits }}
            </FormItem>
          </Col>
        </Row>

        <Row type="flex" justify="space-around">
          <Col span="11">
            <FormItem label="性别：">
              {{ showdata.expertGender }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="邮箱：">
              {{ showdata.email }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around">
          <Col span="11">
            <FormItem label="所在单位：">
              {{ showdata.expertOrgName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="联系方式：">
              {{ showdata.mobileNumber }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around">
          <Col span="23">
            <FormItem label="专业特长：" prop="professionDesc">
              {{ showdata.professionDesc }}
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button @click="onCancel" class='ivu-btn-save'>关闭</Button>
      </div>
    </Modal>
    <Modal title="专家信息修改" :transfer=false v-model="model3" :width=600 @on-cancel="handleCancel3">
      <Form ref="form1datacopy" :model="form1datacopy" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="专家姓名：" prop="userId">
              {{ form1datacopy.userName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="专业积分：" prop="credits">
              <InputNumber style="width:100%" v-model="form1datacopy.credits"></InputNumber>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around">
          <Col span="11">
            <FormItem label="性别：">
              {{ form1datacopy.expertGender }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="邮箱：">
              {{ form1datacopy.email }}
            </FormItem>

          </Col>
        </Row>
        <Row type="flex" justify="space-around">
          <Col span="11">
            <FormItem label="联系方式：">
              {{ form1datacopy.mobileNumber }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="所在单位：">
              {{ form1datacopy.expertOrgName }}
            </FormItem>
          </Col>
        </Row>

        <Row type="flex" justify="space-around">
          <Col span="23">
            <FormItem label="专业特长：" prop="professionDesc">
              <Input v-model="form1datacopy.professionDesc" type="textarea" :rows="4"/>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="submit3('form1datacopy')" :loading="submitButton">确定</Button>
        <Button class='ivu-btn-cancel' @click="handleCancel3">取消</Button>
      </div>
    </Modal>

    <Modal :transfer=false footer-hide v-model="model4" :width=900>
      <userManager :model="true" @getSelectModelData="getSelectModelData"></userManager>
    </Modal>
  </layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
var cascaderDom = () => import('@/components/cascader-dom.vue');
import userManager from '../../../../base/authorityManager/userManager'

export default {
  components: {cascaderDom, userManager},
  data() {
    return {
      addMode: true,
      submitButton:false,
      dutyStatusList: [
        {
          value: '1',
          label: '在职'
        },
        {
          value: '2',
          label: '离职'
        },
        {
          value: '3',
          label: '退休'
        }
      ],
      switchFlag: false,
      form1: {},
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      currentUser: JSON.parse(sessionStorage('userId').get('userId')),
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },

        {
          minWidth: 100,
          title: '专家姓名',
          key: 'userName',
          align: 'center',
        },
        {
          minWidth: 100,
          title: '员工编号',
          key: 'loginId',
          align: 'center',
        },
        {
          minWidth: 150,
          title: '所属二级集团',
          key: 'twoLevelOrgName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '所在单位',
          key: 'expertOrgName',
          align: 'center'
        },
        {
          minWidth: 80,
          title: '专业积分',
          key: 'credits',
          align: 'center'
        },
        //  {
        //     width: '100',
        // 	title: '在职状态',
        // 	key: 'dutyStatus',
        // 	align: 'center'
        // },
        {
          minWidth: 150,
          title: '专业特长',
          key: 'professionDesc',
          align: 'center'
        },

        // {
        //     width: 100,
        //     title: '年龄',
        //     align: 'center'
        // },
        {
          minWidth: 100,
          title: '性别',
          key: 'expertGender',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '联系方式',
          key: 'mobileNumber',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '邮箱',
          key: 'email',
          align: 'center'
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            if (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
            ||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 2);
                    }
                  }
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: "ios-trash",
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                    color: 'red',
                  },
                  on: {
                    click: () => {
                      this.deleteData(params);
                    }
                  }
                }, '删除')
              ]);
            } else {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'},
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'},
                }, '删除')
              ]);
            }
          }
        }
      ],
      currentOrgId: '',
      currentOrgName: '',
      setCurrentName: {},
      ruleCustom: {
        professionDesc: [{required: true, message: '  ', trigger: 'blur,change'}],
        userId: [{required: true, message: '  ', trigger: 'blur,change'}],
        credits: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else if (value < 0) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      form1datacopy: {},
      formnew: {
        credits: 1
      },
      // teamTypes: [],
      // resLevels: [],
      dataTable: [],
      showdata: {},
      model1: false,
      model2: false,
      model3: false,
      model4: false,
      buttonLoading: false,
      add: false,
      tableHeight: 10,
      deleteRows: [],
    }
  },
  mounted: function () {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.query();
  },
  methods: {

    getSelectModelData(row) {
      this.formnew.userId = row.userId;
      this.formnew.userName = row.userName;
      this.model4 = false;
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = window.innerHeight - 220;
      } else {
        this.tableHeight = window.innerHeight - 315;
      }
    },

    setOrgId(data) {
      this.form1.expertOrgId = data[data.length - 1];
    },
    setOrgName(data) {
      this.form1.expertOrgName = data;
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },


    showData(data, flag) {
      this.currentOrgId = data.row.belongOrgId;
      this.currentOrgName = data.row.belongOrgName;
      this.setCurrentName = {value: data.row.contactorId, label: data.row.contactorName};

      if (flag == 1) {
        //查看页面
        this.showdata = data.row;
        this.showdata.setupDate = this.formatDate(new Date(this.showdata.setupDate), 'yyyy-MM-dd');
        this.model2 = true;
      } else {
        //修改页面
        this.form1datacopy = data.row;
        this.addMode = false
        this.model3 = true;
      }
    },

    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    deleteData(params) {

      this.$Modal.confirm({
        title: '提示信息',
        content: '<p>确定删除该条信息</p>',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          let url = Api.adtExpertDelete.replace('/adtexpert','/env/adtexpert');
          this.$http.get(url, {params: {expertId: params.row.expertId}}).then((res) => {
            this.$Message.success('成功');
            this.query()
          }).catch(e => {
            this.$Message.error('请求失败' + e);
          })
        }
      })
    },

    query() {
      this.buttonLoading = true
      let data = {
        currentPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize
      }

      data.userName = this.form1.userName || ''
      data.expertOrgId = this.form1.expertOrgId || ''
      data.professionDesc = this.form1.professionDesc || ''
      let url = Api.adtExpertList.replace('/adtexpert','/env/adtexpert');
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data;
        this.pagedata.total = res.data.totalSize;
        this.buttonLoading = false
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    reset() {
      this.form1 = {}
      this.$refs.childOrg.resetCurrentOrg();
      this.query();

    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    handleCancel3() {
      this.form1datacopy = {};
      this.model3 = false;
        this.query()
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        //console.log(this.formnew)
        let _this = this;
        if (valid) {
          _this.submitButton = true;
          this.$http.post(Api.adtExpertCreate.replace('/adtexpert','/env/adtexpert'), this.formnew).then((res) => {
            if (res.data.status == '200'){
              this.$Message.success("保存成功");
              this.model1 = false;
              this.query();
            }else if(res.data.status == '202'){
              this.$Message.warning(res.data.msg);
              this.model1 = true;
            }else{
              this.$Message.error(res.data.msg);
              this.model1 = false;
              this.query();
            }

            _this.submitButton = false;


          }).catch(e => {
            this.model1 = false;
            this.query();
            _this.submitButton = false;
            this.$Message.error("数据获取失败")
          })
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    submit3(name) {
      this.$refs[name].validate((valid) => {
        //console.log(this.form1datacopy)
        let _this = this;
        if (valid) {
          _this.submitButton = true;
          this.$http.post(Api.adtExpertCreate.replace('/adtexpert','/env/adtexpert'), this.form1datacopy).then((res) => {
            if (res.data.status == '200'){
                _this.$Message.success("保存成功");
                _this.query();
                _this.model3 = false;
            }else if(res.data.status == '202'){
                _this.$Message.warning(res.data.msg);
                _this.model3 = true;
            }else{
                _this.model3 = false;
                _this.query();
            }
              _this.submitButton = false;
          }).catch(e => {
              _this.model3 = false;
              _this.query();
            _this.submitButton = false;
              _this.$Message.error("数据获取失败")
          })
        } else {
            _this.$Message.error('请填报完整!');
        }
      })
    },
    onCancel() {
      this.model2 = false
    },
    addInfo() {
      this.formnew = {credits: 1};
      // this.$refs.childUser.resetCurrentOrg();
      this.currentOrgId = '';
      this.currentOrgName = '';
      this.setCurrentName = {};
      this.model1 = true;
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
  },
}
</script>
<style scoped>
@import '../../../../../index.css';
</style>
